package array.stack;

import java.util.*;

/**
 * @ClassName TopKFrequent
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-02 20:31
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class TopKFrequent {

    /**
     * 347. 前 K 个高频元素
     * 给你一个整数数组 nums 和一个整数 k ，请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
     * <p>
     * 示例 1:
     * <p>
     * 输入: nums = [1,1,1,2,2,3], k = 2
     * 输出: [1,2]
     * 示例 2:
     * <p>
     * 输入: nums = [1], k = 1
     * 输出: [1]
     *
     * @param nums
     * @param k
     * @return
     */
    public int[] topKFrequent(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return nums;
        }


        Map<Integer, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            hashMap.put(nums[i], hashMap.getOrDefault(nums[i], 0) + 1);
        }


        Set<Map.Entry<Integer, Integer>> entries = hashMap.entrySet();

        //大顶堆的实现
        PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((x, y) -> y[1] - x[1]);
        for (Map.Entry<Integer, Integer> entry : entries) {
            priorityQueue.add(new int[]{entry.getKey(), entry.getValue()});
        }

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            int p = priorityQueue.poll()[0];
            result[i] = p;
        }
        return result;
    }

    public static void main(String[] args) {
        TopKFrequent topKFrequent = new TopKFrequent();
        int[] ints = topKFrequent.topKFrequent(new int[]{1, 1, 1, 2, 2, 3,3,3,3}, 2);
        for (int i : ints) {
            System.out.println(i);
        }
    }
}